/*
 * maz_com_string.c
 *
 *  Created on: Jul 27, 2020
 *      Author: Paul
 */

#include "maz_com.h"

/**
 * "dlvl" variables must be defined if debug message is to be printed through the dlog/dmsg, and "dlvl" must be declared static
 */
static int dlvl = DINF;

/**
 * @brief 参考 atoi(ascii to integer)系列函数, 实现ascii to hex
 * @param 输入参数是 0x12; 0x1234 等带有 0x 前缀格式的字符串, 前后没有多余空格
 * @retval 正确转化返回十六进制数的值, 错误转化返回0
 */
int atoh(char *str)
{
    int length = 0;
    int hex = 0;
    int i = 0;

    MAZASSERT_RETVAL(NULL == str, MAZRET_EINVAL, "err: the param str is NULL.");

    length = strlen(str);
    if (length <= 2 || '0' != str[0] || 'x' != str[1])
    {
        dmsg(DERR, "err: input string does not meet the hex format.\r\n");
        return 0;
    }

    for (i = 2; i < length; i++)
    {
        if ((str[i] >= '0') && (str[i] <= '9'))
        {
            hex = hex + ((str[i] - '0') << ((length - 1 - i) << 2));
        }
        else if ((str[i] >= 'a') && (str[i] <= 'z'))
        {
            hex = hex + ((str[i] - 'a' + 10) << ((length - 1 - i) << 2));
        }
        else if ((str[i] >= 'A') && (str[i] <= 'Z'))
        {
            hex = hex + ((str[i] - 'A' + 10) << ((length - 1 - i) << 2));
        }
        else
        {
            dmsg(DERR, "err: input string does not meet the hex format.\r\n");
            return 0;
        }
    }

    return hex;
}
